<template>
    <z-form v-if="inited" url="/api/contract/pdfExport" :fields="['context']" :data="contract">
        <template #context="formData">
            <z-tiptap :modelValue="formData.context" ref="editor" style="margin-bottom: 20px" height="580px"
                mode="readonly" :plugins="plugins" @update:modelValue="update" />
        </template>
    </z-form>
</template>

<script>
import Contract from './blocks/contract/index';
import Material from './blocks/material/index';
export default {
    props: {
        params: Object,
    },
    data() {
        return {
            contract: null,
            inited: false,
            content: null,
            plugins: [Contract, Material],
            fieldsData: {},
            editor: null,
        };
    },
    async created() {
        const result = await $.get({ url: '/api/contract/preview', data: this.params })
        this.contract = result || {}
        this.content = result.context
        if (result.field) {
            result.field.forEach((item) => {
                if (!item.unit) item.unit = ""
                if (item.type != "table") this.fieldsData[item.id] = item.value + item.unit
                else {
                    this.fieldsData[item.id] = this.processTableData(item.value, item.label)
                }
            })
        }
        window._fieldsData = this.fieldsData
        this.inited = true
    },
    methods: {
        // 处理表格数据的方法，返回ProseMirror节点结构
        processTableData(tableData, tableLabel) {
            if (!Array.isArray(tableData)) return null;
            const headers = ['物料名称', '规格', '数量', '计量单位', '含税单价', '总金额'];
            // 创建表头行
            const headerRow = ['tr', ...headers.map(header => ['th', header])];
            // 创建数据行
            const tableRows = tableData.map(item => {
                const rowData = [
                    item.title || '',
                    item.sku || '',
                    item.number + '' || '0',
                    item.unit === 1 ? '个' : '件' || '',
                    item.gstInclusive ? (item.gstInclusive / 100).toFixed(2) + ' 元' : '0.00 元',
                    (item.number * item.gstInclusive).toFixed(2) + ' 元' || '0.00 元'
                ];
                return ['tr', ...rowData.map(cell => ['td', cell])];
            });
            // 返回表格结构
            return [
                "div", { class: "material-container" },
                ["h3", { class: "material-title" }, tableLabel],
                [
                    "table", { class: "material-table" },
                    ["thead", headerRow],
                    ["tbody", ...tableRows]
                ]
            ];
        }
    },
}
</script>
